package com.example.mvvmdemo.repository;

import android.os.AsyncTask;
import android.util.Log;

import androidx.lifecycle.LiveData;

import com.example.mvvmdemo.api.Api;
import com.example.mvvmdemo.db.UserDao;
import com.example.mvvmdemo.model.User;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @author: tuyrt7 on 2020/8/31.
 * Describe:
 */
public class UserRepository {

    private String TAG = this.getClass().getSimpleName();
    private UserDao mUserDao;
    private Api mApi;

    public UserRepository(UserDao userDao, Api api) {
        mUserDao = userDao;
        mApi = api;
    }

    public LiveData<User> getUser(String name) {
        refresh(name);
        return mUserDao.getUserByName(name);
    }

    public void refresh(String name) {
        mApi.getUser(name).enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                Log.d(TAG, "onResponse: "+response.body().toString());
                if (response.body() != null) {
                    insertUser(response.body());
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {

            }
        });
    }

    private void insertUser(final User user) {
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                mUserDao.insertUser(user);
            }
        });
    }
}
